import { useMutation } from '@tanstack/vue-query'
import { useRouter } from 'vue-router'

import { useArcoForm } from '@/composables/useArcoForm'
import { useFetchMessage } from '@/composables/useFetchMessage'
import { useUserStore } from '@/stores/user'

import { ApiUpdatePassword, userMessage } from '@/apis/user'
import { RouterName } from '@/router/name'
import { useToggle } from '@vueuse/core'

export type FormState = Record<'oldPassword' | 'newPassword' | 'confirmPassword', string>
export function useUpdatePassword() {
  const [visible, toggleVisible] = useToggle()
  const { formState, formRef, validate, onValidateSuccess } = useArcoForm({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })

  const router = useRouter()
  const userStore = useUserStore()
  const { showMessage } = useFetchMessage([userMessage])

  const { mutate, isPending } = useMutation({
    mutationFn: ApiUpdatePassword,
    onSettled(data, error) {
      showMessage(data?.code ?? error?.data?.code)
    },
    async onSuccess() {
      userStore.logout()
      await router.push({ name: RouterName.Login })
    }
  })

  onValidateSuccess(({ confirmPassword: _, ...data }) => {
    mutate({ username: userStore.user.username, ...data })
  })

  return {
    visible,
    toggleVisible(value?: boolean) {
      isPending.value || toggleVisible(value)
    },

    formRef,
    formState,
    isPending,
    validate
  }
}
